package eirkdbd.lab1.membership.functions.helpers;

import org.apache.commons.math3.stat.regression.SimpleRegression;


/**
 * Crates helper for linear function value computing. </br>
 * Linear function coefficients are computed on the basis of points of min and max value </br>
 * For positive a parameter :
 * <ul>
 * <li>	f(x>=max) = 1
 * <li> f(x<=min) = 0
 * </ul>
 * For negative a parameter :
 * <ul>
 * <li>	f(x>=max) = 0
 * <li> f(x<=min) = 1
 * </ul>
 */
public class LinearMembershipFunction {

	private double a;
	private double b;
	private double minX;
	private double maxX;
	
	public LinearMembershipFunction(double minX, double maxX) {
		if (minX == maxX)
			throw new IllegalArgumentException("Points of Min and Max can't be equal");
		this.minX = minX;
		this.maxX = maxX;
		computeCoefficients();
	}
	
	private void computeCoefficients() {
		SimpleRegression simpleRegression = new SimpleRegression();
		simpleRegression.addData(minX, 0.);
		simpleRegression.addData(maxX, 1.);
		a = simpleRegression.getSlope();
		b = simpleRegression.getIntercept();
	}

	public double value(double x){
		if (maxX > minX)
			return positiveFunctionValue(x);		
		else 
			return negativeFunctionValue(x);		
	}
	
	private double negativeFunctionValue(double x){
		if (x >= minX)
			return 0;
		else if ( x <= maxX)
			return 1;
		else 
			return  a*x + b;				
	}
	
	private double positiveFunctionValue(double x){
		if (x >= maxX)
			return 1;
		else if (x <= minX)
			return 0;
		else 
			return a*x + b;			
	}	
}
